<!--
 * @Description: 
 * @version: 
 * @Author: erze
 * @Date: 2021-05-18 16:39:37
 * @LastEditors: erze
 * @LastEditTime: 2021-05-19 08:14:35
-->
<template>
  <div class="z-form-item">
      <!-- 插槽 -->
      <label>
          <span>{{label}}</span>
          <slot></slot>
      </label>
      <div class="errMsg" v-show="errMsg">
          {{errMsg}}
      </div>
  </div>
</template>

<script>
import Schema from 'async-validator'

export default {
    // 获取祖先的参数
    inject: ['form'],
    created() {
        // 监听 validate 事件是否触发
        this.$on('validate', () => {
            this.validate()
        })
    },
    props: {
        label: {
            type: String,
        },
        prop: {
            type: String,
        }
    },
    data(){
        return{
            errMsg:'',
        }
    },
    methods: {
        // 单条校验
        validate() {
            // 需要用到rules
            const rules = this.form.rules[this.prop];
            const value = this.form.model[this.prop];
            
            const schema = new Schema({[this.prop]: rules})
            return schema.validate({[this.prop]:value}, (err) => {
               if(err) {
                   this.errMsg = err[0].message;
               }else{
                   this.errMsg = '';
               }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.z-form-item{
    width: 40vw;
    height: 40px;
    margin-bottom: 22px;
    label{
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        span{
            width: 30%;
        }
    }
}
</style>